package com.uduemc.biso.node.web.service.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.pojo.ICP35;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.service.AsyncDomainService;
import com.uduemc.biso.node.web.service.byfeign.DomainService;

@Service
public class AsyncDomainServiceImpl implements AsyncDomainService {

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private DomainService domainServiceImpl;

	@Override
	@Async
	public void asyncCacheIcpDomain(HDomain hDomain, long expire, long noicpexpire) {
		String domain = hDomain.getDomainName();
		ICP35 icp35 = null;
		try {
			icp35 = domainServiceImpl.getIcpDomain(domain);
		} catch (IOException e) {
		}
		if (icp35 == null || icp35.getResult() == -1) {
			return;
		}
		String KEY = globalProperties.getSiteRedisKey().getIcpDomainCachekey(domain);
		if (icp35.getResult() == 1) {
			redisUtil.set(KEY, icp35, expire);
		} else if (icp35.getResult() == 0) {
			redisUtil.set(KEY, icp35, noicpexpire);
		}
		try {
			String remark = objectMapper.writeValueAsString(icp35);
			if (icp35.getResult() == 1) {
				hDomain.setStatus((short) 1);
			} else if (icp35.getResult() == 0) {
				hDomain.setStatus((short) 2);
			}
			hDomain.setRemark(remark);
			domainServiceImpl.updateAllById(hDomain);
		} catch (IOException e) {
		}
	}

	@Override
	@Async
	public void asyncCacheIcpDomain(String domain, long expire, long noicpexpire) {
		ICP35 icp35 = null;
		try {
			icp35 = domainServiceImpl.getIcpDomain(domain);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (icp35 != null) {
			if (icp35 != null && icp35.getResult() != -1) {
				String KEY = globalProperties.getSiteRedisKey().getIcpDomainCachekey(domain);
				if (icp35.getResult() == 1) {
					redisUtil.set(KEY, icp35, expire);
				} else if (icp35.getResult() == 0) {
					redisUtil.set(KEY, icp35, noicpexpire);
				}
			}
		}
	}

}
